<template>
	<view class="content">

		<view class="item-box">
			<view class="item-left">
				<view class="item-line-v"></view>
				<view class="item-title">患者信息</view>
			</view>
		</view>
		<view class="yy-inquiry-user-info" v-if="patient_info.id" @click="selPatient">
			<view class="user-left">
				<view class="icon">
					<image v-if="patient_info.avatar" :src="patient_info.avatar" mode="aspectFill">
					</image>
					<image v-else src="@/static/images/f.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="user-right">
				<view class="info">
					{{ infoFormat(patient_info) }}
				</view>
				<view class="detail">
					{{ bodyStatae(patient_info)}}
				</view>
			</view>
		</view>
		<view class="yy-inquiry-user-sel" v-else @click="selPatient">
			<text class="iconfont icon-jiahao1"></text>
			<view class="">选择患者</view>
		</view>

		<view class="item-box">
			<view class="item-left">
				<view class="item-line-v"></view>
				<view class="item-title">问题描述</view>
			</view>
			<view class="item-right" @click="clickExample">
				<view class="right-title">描述示例</view>
				<text class='iconfont icon-xiangxia'></text>
			</view>
		</view>
		<view class="des-box">
			<view class="input-box">
				<textarea :placeholder="desPlaceHolder" v-model="desContent" />
			</view>
			<view class="quick-box">
				<view class="quick-item" v-for="(item,index) in quickType" @click="clickQuickItem(item)">
					+{{item.title}}
				</view>
			</view>
		</view>
		<!-- 指导 -->
		<view class="d-guide" @click="changeGuide">
			<text v-if="guideValue == 1" class="guide-icon iconfont icon-xuanzhong1"></text>
			<text v-else class="guide-icon iconfont icon-weixuanzhong"></text>
			<view class="guid-title">需要医生指导用药</view>
		</view>
		
		<!-- 图集 -->
		<view class="item-box no-bot">
			<view class="item-left">
				<view class="item-line-v"></view>
				<view class="item-title">上传图片</view>
			</view>
		</view>
		<view class="upload-img">
			<view class="img-wrapper" v-if="uploadImg.length>0" v-for="(item,index) in uploadImg">
				<image :src="item"></image>
				<view class="iconfont icon-guanbi1" @click="deleteImg(index)"></view>
			</view>
			<view class="add-img" @click="uploadpic" v-if="isUpload">
				<view class="add-item">
					<text class="iconfont icon-jiahao1"></text>
				</view>
			</view>
			<view class="uplod-des-box" v-if="uploadImg.length == 0">
				<view class="des-text">
					上传检查报告或患处照片(最多9张)
				</view>
				<view class="des-text">
					照片仅自己和医生可见
				</view>
			</view>

		</view>

		<view class="item-box">
			<view class="item-left">
				<view class="item-line-v"></view>
				<view class="item-title">服务权益</view>
			</view>
		</view>
		<view class="server-box">
			<view class="server-des" v-for="(item,index) in inquiryInfo.server_info">
				{{item}}
			</view>
		</view>

		<!-- 隐私 -->
		<view class="d-guide" @click="changeAgree" v-if="inquiryInfo.know_agree">
			<text v-if="agreeValue == 1" class="guide-icon iconfont icon-xuanzhong1"></text>
			<text v-else class="guide-icon iconfont icon-weixuanzhong"></text>
			<view class="guid-title">我已阅读并同意<text class="agreement"
					@click.stop="clickAgree1">《{{ inquiryPost1.title }}》</text><text class="agreement"
					@click.stop="clickAgree2">《{{ inquiryPost2.title }}》</text></view>
		</view>

		<!-- 提交 -->
		<view class="submit-box">
			<view class="price-box">
				<view class='txt'>￥</view>
				<view class='txt txt1'>{{doctor_price}}</view>
			</view>
			<view :class="submitEnable ? 'submit-btn':'submit-btn unenable' " @click="clickSubmit">立即支付</view>
		</view>
		<view class="yy-safe-bh"></view>

		<!-- 示例弹窗 -->
		<uni-popup ref="desPopup" type="center">
			<view class="pop-box">
				<view class="pop-title">示例</view>
				<view class="pop-ex-box">
					<view class="ex-desc" v-for="(item,idx) in inquiryInfo.desc">
						{{item}}
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 支付弹窗 -->
		<payment :payMode="payMode" :pay_close="pay_close" @onChangeFun="onChangeFun" :order_id="pay_order_id"
			:totalPrice="doctor_price" :order_type="order_type"></payment>

	</view>
</template>

<script>
	let app = getApp();
	import {
		mapGetters
	} from "vuex";

	import {
		createPicTextOrder,
		createAudioOrder,
		getInquiryInfo
	} from '@/api/inquiry.js';

	import {
		getUserInfo
	} from "@/api/user";
	import payment from "@/components/payment";

	import {
		userinfoFormat,
		userBodyStataeFormat
	} from "@/utils/format.js";

	export default {
		components: {
			payment
		},
		computed: {
			...mapGetters(['userInfo', 'uid','routeError'])
		},
		data() {
			return {
				doctor_id: '',
				doctor_price: '0',
				inquiryInfo: {},
				inquiryPost1:{},
				inquiryPost2:{},
				patient_info: {},
				desPlaceHolder: '为更快速有效获取医生帮助,请尽量详细描述您的问题,如：症状发病时间、用药情况、过往病史等(不少于10个字)',
				desContent: '',
				quickType: [{
					'id': 0,
					'title': '症状描述'
				}, {
					'id': 1,
					'title': '患病时长'
				}, {
					'id': 2,
					'title': '医院检查'
				}, {
					'id': 3,
					'title': '用药情况'
				}, ],
				guideValue: 0,
				uploadImg: [],
				isUpload: true,
				agreeValue: 0,
				submitEnable: false,

				pay_close: false,
				pay_order_id: "",
				payMode: [{
						name: "微信支付",
						icon: "icon-weixinzhifu",
						value: "wechat",
						title: "微信快捷支付",
						payStatus: 1
					},
					{
						name: "支付宝支付",
						icon: "icon-zhifubao",
						value: "alipay",
						title: "支付宝支付",
						payStatus: app.globalData.alipay_open
					},
					{
						name: "余额支付",
						icon: "icon-yuezhifu",
						value: "balance",
						title: "可用余额:",
						number: 0,
						payStatus: app.globalData.yue_pay_status
					}
				],
				conversation_id: '',
				doc_mer_id:'',
				audio_time:'',
				isRtc:false,
				order_type:4,//参考payment插件说明
			}
		},
		watch: {
			uploadImg(nVal, oVal) {
				this.isUpload = nVal.length < 9 ? true : false
				this.checkEnable();
			},
			desContent(nVal, oVal) {
				this.checkEnable();
			},
			userInfo(nVal, oVal) {
				//console.log('rk==>[info]' + JSON.stringify(nVal))
			}
		},
		onLoad(ops) {
			if(this.routeError) {
				this.$store.commit('GO_ERROR');
				return
			}
			if (!ops || !ops.doctor_id || !ops.mer_id) {
				return this.$util.Tips({
					title: '缺少参数',
				})
			}
			this.doctor_id = ops.doctor_id;
			this.doctor_price = ops.price;
			this.doc_mer_id = ops.mer_id;
			if(ops.selType == 3){
				uni.setNavigationBarTitle({
					title:'图文问诊'
				})
			}else {
				uni.setNavigationBarTitle({
					title:'视频问诊'
				})
			}
			if(ops.audio_time) {
				this.order_type = 6;
				this.isRtc = true;
				this.audio_time = JSON.parse(decodeURIComponent(ops.audio_time));
			}
			
			//页面信息
			this.getInquiryInfo();

			// 监听选择患者
			this.$nextTick(() => {
				let that = this;
				uni.$on('yy_patient_sel', data => {
					//console.log('rk===>sel suc:' + JSON.stringify(data))
					that.patient_info = data;
					that.checkEnable();
				});
			});

		},
		onShow() {
			// 获取余额
			this.getUserInfo();
		},
		onUnload() {
			uni.$off('yy_patient_sel');
		},
		methods: {
			/**
			 * 获取用户信息
			 *
			 */
			getUserInfo: function() {
				let that = this;
				getUserInfo()
					.then(res => {
						that.payMode[2].number = res.data.now_money;
						// that.$set(that, 'payMode', that.payMode);
					})
					.catch(err => {
						return this.$util.Tips({
							title: err
						});
					});
			},
			/**
			 * 问诊页面信息
			 */
			getInquiryInfo() {
				getInquiryInfo().then(res => {
					this.inquiryInfo = res.data;
					this.inquiryPost1 = res.data.know_agree;
					this.inquiryPost2 = res.data.privacy_agree;
					//console.log('rk==>[res]' + JSON.stringify(this.inquiryPost1));
					//console.log('rk==>[res]' + JSON.stringify(this.inquiryPost2));

				});
			},
			/**
			 * 选择患者
			 */
			selPatient() {
				uni.navigateTo({
					url: '/pages/shops/subs_inquiry/patients/index'
				})
			},
			/**
			 * 信息格式化
			 */
			infoFormat(info) {
				return userinfoFormat(info);
			},
			/**
			 * 状态格式化
			 */
			bodyStatae(info) {
				return userBodyStataeFormat(info);
			},
			/**
			 * 示例
			 */
			clickExample() {
				this.$refs.desPopup.open();
			},
			/**
			 * 快捷描述
			 */
			clickQuickItem(item) {
				let nextLine = '';
				if (this.desContent.length > 0) {
					nextLine = '\n';
				}
				this.desContent = this.desContent + nextLine + item.title + ':';
				
			},
			/**
			 * 医生指导
			 */
			changeGuide() {
				if (this.guideValue == 1) {
					this.guideValue = 0;
				} else {
					this.guideValue = 1;
				}
			},
			/**
			 * 上传文件
			 * 
			 */
			uploadpic: function() {
				let that = this;
				let opt = {url:'upload/image',
						   count:9-that.uploadImg.length}
				// that.$util.uploadImageOne(opt, function(res) {
				// 	console.log('rk==>[上传]' + JSON.stringify(res));
				// 	that.uploadImg.push(res.data.path);
				// 	that.$set(that, 'uploadImg', that.uploadImg);
				// });
				that.$util.uploadImagesMany(opt, function(res) {
					// console.log(res);
					for (let i = 0; i < res.length; i++) {
						that.uploadImg.push(res[i]) 
					}
					// console.log(that.uploadImg);
					that.$set(that, 'uploadImg', that.uploadImg);
				});
			},
			/**
			 * 删除图片
			 */
			deleteImg(index) {
				this.uploadImg.splice(index, 1)
			},
			/**
			 * 协议
			 */
			changeAgree() {
				if (this.agreeValue == 1) {
					this.agreeValue = 0;
				} else {
					this.agreeValue = 1;
				}

				this.checkEnable();
			},
			clickAgree1() {
				this.goPost(1);
			},
			clickAgree2() {
				this.goPost(2);
			},
			goPost(param) {
				let paramJson = encodeURIComponent(JSON.stringify(this.inquiryPost1));
				if(param == 2){
					paramJson = encodeURIComponent(JSON.stringify(this.inquiryPost2));
				}
				uni.navigateTo({
					url: '/pages/shops/subs_inquiry/picture_text/inquiryPost?param=' + paramJson
				});
			},

			/**
			 * 检测提交
			 */
			checkEnable() {
				this.submitEnable = false;

				if (this.desContent.length <= 0) {
					return
				}
				if (this.agreeValue != 1) {
					return
				}
				if (!this.patient_info || !this.patient_info.id) {
					return
				}
				this.submitEnable = true;
			},
			/**
			 * 准备支付
			 */
			clickSubmit() {
				
				if(!this.submitEnable){
					return
				}
				
				// 字符统计
				let previewDes = this.desContent;
				this.quickType.forEach(item => {
					// console.log("rk===>[foreach]" + item.title);
					let filterStr = item.title+':';
					previewDes = previewDes.replace(RegExp(filterStr, "g"),'');
				}); 
				previewDes = previewDes.replace(/[\r\n]/g,'');
				// console.log("rk===>[原始]" + JSON.stringify(this.desContent));
				// console.log("rk===>[统计]" + JSON.stringify(previewDes));
				
				if (previewDes.length <= 10) {
					return this.$util.Tips({
						title: '问题描述不能少于10个字'
					});
				}

				let picJosn = '';
				if (this.uploadImg.length > 0) {
					picJosn = encodeURIComponent(JSON.stringify(this.uploadImg));
				}
				let param = {
					'uid': this.uid,
					'doctor_id': this.doctor_id,
					'patient_id': this.patient_info.id,
					'describe': this.desContent,
					'is_guide': this.guideValue,
					'pic': picJosn,
				}
				
				// rk_ 判断图文还是音视频
				let reqApi = createPicTextOrder;
				if(this.isRtc) {
					param.audio_time = this.audio_time;
					reqApi = createAudioOrder;
				}
				console.log('rk==>[res]'+JSON.stringify(param));
				
				let that = this;
				/**
				 * rk_tips
				 * 1.请求创建订单、
				 * 2.弹出支付弹窗
				 * 3.支付完成跳转问诊
				 */
				uni.showLoading({
					title: '请稍后...'
				});
				reqApi(param).then(res => {
					console.log('rk==>[res]' + JSON.stringify(res));
					uni.hideLoading();
					if (res.status != 200) {
						return that.$util.Tips({
							title: res.message
						});
					}
					this.$set(this, "pay_close", true);
					this.pay_order_id = res.data.doctor_order_key;
					//rk_ 需要会话ID
					this.conversation_id = res.data.conversation_id;
				
				}).catch(err => {
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
				
				
			},
			/**
			 * 事件回调
			 *
			 */
			onChangeFun: function(e) {
				console.log('rk==>' + JSON.stringify(e));
				let opt = e;
				let action = opt.action || null;
				let value = opt.value != undefined ? opt.value : null;
				action && this[action] && this[action](value);
			},
			/**
			 * 关闭支付组件
			 *
			 */
			payClose: function() {
				this.pay_close = false;
				this.$emit("payClose");
			},
			/**
			 * 支付失败回调
			 *
			 */
			pay_fail: function() {
				this.pay_close = false;
				this.pay_order_id = "";
			},
			/**
			 * 支付成功回调
			 *
			 */
			pay_complete: function() {
				this.pay_close = false;
				this.pay_order_id = "";
				//console.log('rk==>[支付成功哦]');
				// conversation_id
				
				let that = this;
				if(this.isRtc){
					let yyMerId = this.doc_mer_id;
					
					let patientID = this.patient_info.id;
					// conversition_type:0-图文  1-在线  2-视频
					// can_refund: 1-能取消  0-不能取消【当type=2时有效】
					
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/chat/customer_list/chath5?conversation_id=' 
							+ that.conversation_id 
							+'&patient_id='+patientID
							+'&mer_id='+yyMerId
							+'&send_tips=1'
							+'&conversition_type=2'
							+'&can_refund=1'
						})
					}, 2000);
				}else {
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/shops/subs_inquiry/record/picTextDetail?conversation_id=' + that
								.conversation_id + '&mer_id='+ that.doc_mer_id,
						})
					}, 2000);
				}
			},

		}
	}
</script>

<style lang="scss">
	page {
		flex: 1;
		background-color: #fff;
	}

	.content {
		background-color: #fff;
		padding: 10rpx 30rpx;
	}
	.no-bot {
		padding-bottom: 0 !important;
	}
	.item-box {
		width: 100%;
		padding: 30rpx 0rpx;
		font-size: $yy-title-font;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.item-left {
			display: flex;
			align-items: center;

			.item-line-v {
				width: 10rpx;
				border-radius: 10rpx;
				height: 30rpx;
				background-color: $yy-main-col;
				margin-right: 10rpx;
			}
		}

		.item-right {
			display: flex;
			align-items: center;
			color: $yy-main-col;

			.right-title {
				font-size: 20rpx;
			}

			.iconfont {
				padding-left: 5rpx;
			}
		}
	}

	.des-box {
		background-color: #fafafa;
		// width: 100%;
		border-radius: 10rpx;
		padding: 2rpx 10rpx 10rpx 10rpx;
		// display: flex;

		textarea {
			width: 100%;
			height: 260rpx;
			margin-top: 30rpx;
			padding: 0rpx 20rpx 0;
			font-size: 28rpx;
			line-height: 1.5;
		}

		.quick-box {
			display: flex;
			justify-content: space-around;
			margin: 20rpx 0 10rpx;

			.quick-item {
				background-color: #f5f5f5;
			}
		}
	}

	.d-guide {
		display: flex;
		align-items: center;
		margin: 20rpx 0;
		font-size: $yy-title-font;
	}

	.guide-icon {
		color: $yy-main-col;
	}

	.guid-title {
		margin-left: 5rpx;
	}

	.upload-img {
		display: flex;
		flex-wrap: wrap;

		.img-wrapper {
			position: relative;
			display: flex;
			justify-content: center;
			flex-wrap: wrap;
			margin: 30rpx 0rpx 20rpx 0;
			width: 33%;
			height: 158rpx;

			image {
				width: 158rpx;
				height: 158rpx;
			}

			.iconfont {
				position: absolute;
				right: -15rpx;
				top: -20rpx;
				font-size: 40rpx;
				color: var(--view-theme);
			}

			&:nth-child(3n) {
				margin-right: 0;
			}
		}

		.add-img {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 33%;
			height: 158rpx;
			margin-top: 30rpx;
			margin-bottom: 20rpx;

			.add-item {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 158rpx;
				height: 158rpx;
				background: #F5F5F5;
				border-radius: 10rpx;
				border: 1rpx solid $yy-main-col;
			}

			.iconfont {
				color: $yy-main-col;
				font-size: 55rpx;
			}
		}

		.uplod-des-box {
			width: 66%;
			height: 158rpx;
			margin-top: 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: flex-start;
			flex-direction: column;
			justify-content: center;
		}
	}

	.server-box {
		padding: 0 15rpx;

		.server-des {
			font-size: 28rpx;
			color: #969696;
		}
	}

	.agreement {
		color: $yy-main-col;
	}

	.submit-box {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		margin: 50rpx 0;

		.price-box {
			display: flex;
			align-items: baseline;

			.txt {
				color: #ff4f00;
			}

			.txt1 {
				font-size: 30px;
				font-weight: bold;
			}
		}

		.submit-btn {
			background-color: $yy-main-col;
			width: 120px;
			height: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			border-radius: 100rpx;
		}

		.unenable {
			background-color: $yy-main-light-col;
		}
	}

	// 弹窗
	.pop-box {
		background-color: #fff;
		border-radius: 10rpx;
		width: 600rpx;
		height: 500rpx;

		.pop-title {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx 0;
		}

		.pop-ex-box {
			margin: 20rpx;
		}

		.ex-desc {
			font-size: 30rpx;
		}
	}
</style>
